<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>\
    <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>

</head>

<body>
    <h1>取消请求</h1>
    <input type="text" id="ipt">
    <button id="btn">提交</button>
    <button id="cancel">取消请求</button>
    <script>
        const myAxios = axios.create({
            baseURL: '/',
            timeout: 10000,
            headers: {}
        })
        const oIpt = document.getElementById('ipt')
        const oBtn = document.getElementById('btn');
        const oCancel = document.getElementById('cancel');
        //拿到一个取消请求的对象(是一个构造函数)
        const CancelToken = axios.CancelToken;
        // 声明一个全局变量
        let cancel = null;
        oBtn.onclick =async function(){
            const iptValue = oIpt.value;
            try{
                const re= await myAxios.get('/userLazy',{
                    params:{
                        userId: iptValue,
                    },
     //在配置对象中配置一个cancelToken的配置项,值是实例化的CancelToken对象
                 CancelToken: new CancelToken((c)=>{
                    console.log(c);
             //当请求发送的时候,这个回调函数会被执行,并接受一个参数,这个参数其实就是取消当前请求的函数
             cancel=c   
                 })      
                })
                console.log(re);
            }catch(e){
                console.log(e.message, "出现错误");
            }
        }
         //取消请求点击事件
         oCancel.onclick=function(){
            cancel()
         }
    </script>
</body>

</html>